<template>
  <view class="viewport">
    <CustomNavbar />
    <scroll-view
      enable-back-to-top
      refresher-enabled
      class="scroll-view"
      scroll-y
      @scrolltolower="onScrolltolower"
    >
      <XtxSwiper :bannerList="bannerList" />
      <CategoryComponent :list="categoryList" />
      <HotPanel :list="hotShopList" />
      <XtxGuess :list="guessList" ref="guessRef" />
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import CustomNavbar from "@/pages/Home/components/CustomNavbar.vue";
import XtxSwiper from "@/components/XtxSwiper.vue";
import CategoryComponent from "@/pages/Home/components/Category.vue";
import HotPanel from "@/pages/Home/components/HotPanel.vue";
import XtxGuess from "@/components/XtxGuess.vue";
import type { BannerItem, CategoryItem, HotShopItem } from "@/types/index";
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from "@/service/home";
import { getGuess } from "@/service/guess";
import { ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import type { Data } from "@/utils/http";
import type { GuessItem, pageParams, pageResult } from "@/types/index";

const guessRef = ref<InstanceType<typeof XtxGuess>>();
const pageParamData = ref<pageParams>({
  page: 1,
  pageSize: 10,
});
const guessList = ref<GuessItem[]>([]);
// 获取·猜你喜欢·数据
const loadGuessData = async () => {
  try {
    const res = (await getGuess(pageParamData.value)) as Data<pageResult<GuessItem>>;
    // 修正为正确的数据结构
    guessList.value = res.result.items || [];
  } catch (error) {
    console.log(error);
  }
};
// 获取banner数据
const bannerList = ref<BannerItem[]>([]);
const getHomeBannerData = async () => {
  const res = (await getHomeBannerAPI()) as Data<BannerItem[]>;
  bannerList.value = res.result.length > 0 ? res.result : [];
};
// 获取分类数据
const categoryList = ref<CategoryItem[]>([]);
const getCategoryData = async () => {
  const res = (await getHomeCategoryAPI()) as Data<CategoryItem[]>;
  categoryList.value = res.result.length > 0 ? res.result : [];
};
// 获取热卖商品
const hotShopList = ref<HotShopItem[]>([]);
const getHotShopData = async () => {
  const res = (await getHomeHotAPI()) as Data<HotShopItem[]>;
  hotShopList.value = res.result.length > 0 ? res.result : [];
};

// 监听滚动到底部
const onScrolltolower = () => {
  pageParamData.value.pageSize! += 10;
  loadGuessData();
};

// 页面加载
onLoad(async () => {
  await Promise.all([getHomeBannerData(), getCategoryData(), getHotShopData(), loadGuessData()]);
});
</script>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  overflow: hidden;
}

.viewport {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.scroll-view {
  flex: 1;
  overflow: hidden;
}
</style>
